<template>
  <div class="archive-storage-retrieval-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>档案存储与检索</span>
      </div>
      
      <!-- 搜索控制区域 -->
      <div class="search-controls">
        <!-- 搜索方式选择 -->
        <div class="search-mode-selector">
          <el-radio-group v-model="searchMode" @change="onSearchModeChange">
            <el-radio-button label="mysql">传统搜索</el-radio-button>
            <el-radio-button label="elasticsearch" :disabled="!elasticsearchAvailable">
              智能搜索
              <el-tooltip content="基于Elasticsearch的全文搜索，支持内容语义匹配" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </el-radio-button>
          </el-radio-group>
          
          <!-- ES状态指示器 -->
          <div class="es-status" v-if="searchMode === 'elasticsearch'">
            <el-tag :type="elasticsearchAvailable ? 'success' : 'danger'" size="mini">
              <i :class="elasticsearchAvailable ? 'el-icon-success' : 'el-icon-error'"></i>
              {{ elasticsearchAvailable ? 'ES可用' : 'ES不可用' }}
            </el-tag>
            <el-button 
              size="mini" 
              type="text" 
              @click="checkElasticsearchStatus"
              :loading="esStatusChecking">
              刷新状态
            </el-button>
          </div>
        </div>

        <!-- 搜索栏 -->
        <div class="search-bar">
          <el-input 
            :placeholder="searchMode === 'elasticsearch' ? '请输入关键词进行智能搜索（支持内容全文检索）' : '请输入标题、类型或位置关键词'" 
            v-model="searchQuery" 
            class="input-with-select" 
            @keyup.enter.native="fetchArchives"
            clearable>
            <el-button slot="append" icon="el-icon-search" @click="fetchArchives"></el-button>
          </el-input>
        </div>

        <!-- 同步控制 -->
        <div class="sync-controls" v-if="searchMode === 'elasticsearch' && elasticsearchAvailable">
          <el-button 
            size="small" 
            type="primary" 
            plain
            @click="syncToElasticsearch"
            :loading="syncing">
            <i class="el-icon-refresh"></i>
            同步数据到ES
          </el-button>
        </div>
      </div>

      <!-- 搜索提示 -->
      <div class="search-tips" v-if="searchMode === 'elasticsearch'">
        <el-alert
          title="智能搜索提示"
          type="info"
          :closable="false"
          show-icon>
          <template slot="default">
            智能搜索基于Elasticsearch全文检索，支持：
            <ul>
              <li>档案标题、内容的模糊匹配</li>
              <li>OCR识别文本的全文搜索</li>
              <li>智能相关性排序</li>
            </ul>
          </template>
        </el-alert>
      </div>

      <el-table :data="archives" style="width: 100%" v-loading="loading">
        <el-table-column prop="archiveId" label="ID" width="80"></el-table-column>
        <el-table-column prop="title" label="档案标题"></el-table-column>
        <el-table-column prop="archiveType" label="档案类型" width="120"></el-table-column>
        <el-table-column prop="securityLevel" label="保密等级" width="120"></el-table-column>
        <el-table-column prop="receiptTime" label="接收时间" width="180"></el-table-column>
        <el-table-column prop="status" label="状态" width="100"></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" @click="viewArchiveDetails(scope.row)">详情</el-button>
            <el-button size="mini" type="primary" @click="downloadArchive(scope.row)" 
                       :disabled="!scope.row || !scope.row.filePath">
              <i class="el-icon-download"></i>
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalArchives">
      </el-pagination>
    </el-card>

    <!-- 档案详情对话框 -->
    <el-dialog title="档案详情" :visible.sync="detailDialogVisible" width="60%">
      <div v-if="currentArchive">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="档案ID">{{ currentArchive.archiveId }}</el-descriptions-item>
          <el-descriptions-item label="档案标题">{{ currentArchive.title }}</el-descriptions-item>
          <el-descriptions-item label="档案类型">{{ currentArchive.archiveType }}</el-descriptions-item>
          <el-descriptions-item label="保密等级">{{ currentArchive.securityLevel }}</el-descriptions-item>
          <el-descriptions-item label="物理位置">{{ currentArchive.physicalLocation || '无' }}</el-descriptions-item>
          <el-descriptions-item label="可见范围">{{ currentArchive.visibleScope }}</el-descriptions-item>
          <el-descriptions-item label="接收时间">{{ currentArchive.receiptTime }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ currentArchive.status }}</el-descriptions-item>
          <el-descriptions-item label="自动分类">{{ currentArchive.autoCategory || '无' }}</el-descriptions-item>
          <el-descriptions-item label="自动标签">{{ currentArchive.autoTags || '无' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentArchive.createdAt }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ currentArchive.updatedAt }}</el-descriptions-item>
        </el-descriptions>
        
        <!-- 文档内容展示 -->
        <div class="ocr-content-section" v-if="currentArchive.ocrContent">
          <h4>文档内容</h4>
          <el-input
            type="textarea"
            :rows="8"
            v-model="currentArchive.ocrContent"
            :readonly="true"
            placeholder="无文档内容">
          </el-input>
        </div>
        <div class="ocr-content-section" v-else>
          <h4>文档内容</h4>
          <el-alert
            title="该档案没有文档内容"
            type="info"
            :closable="false"
            show-icon>
          </el-alert>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="downloadArchive(currentArchive)" 
                   :disabled="!currentArchive || !currentArchive.filePath">
          <i class="el-icon-download"></i>
          下载文件
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import service from '@/utils/request';
import { downloadArchive } from '@/utils/download';

export default {
  name: 'ArchiveStorageRetrieval',
  data() {
    return {
      archives: [],
      currentPage: 1,
      pageSize: 10,
      totalArchives: 0,
      searchQuery: '',
      detailDialogVisible: false,
      currentArchive: null,
      loading: false,
      searchMode: 'mysql', // 'mysql' 或 'elasticsearch'
      elasticsearchAvailable: false,
      esStatusChecking: false,
      syncing: false
    };
  },
  created() {
    this.checkElasticsearchStatus();
    this.fetchArchives();
  },
  methods: {
    async checkElasticsearchStatus() {
      this.esStatusChecking = true;
      try {
        const res = await service.get('/archive/elasticsearch/status');
        if (res.data.code === 200) {
          this.elasticsearchAvailable = res.data.data;
          if (!this.elasticsearchAvailable && this.searchMode === 'elasticsearch') {
            this.searchMode = 'mysql';
            this.$message.warning('Elasticsearch不可用，已切换到传统搜索模式');
          }
        }
      } catch (error) {
        console.error("检查Elasticsearch状态失败:", error);
        this.elasticsearchAvailable = false;
        if (this.searchMode === 'elasticsearch') {
          this.searchMode = 'mysql';
          this.$message.warning('Elasticsearch连接失败，已切换到传统搜索模式');
        }
      } finally {
        this.esStatusChecking = false;
      }
    },
    onSearchModeChange(newMode) {
      if (newMode === 'elasticsearch' && !this.elasticsearchAvailable) {
        this.$message.warning('Elasticsearch不可用，无法切换到智能搜索模式');
        this.searchMode = 'mysql';
        return;
      }
      
      console.log('搜索模式切换到:', newMode);
      this.currentPage = 1; // 重置页码
      this.fetchArchives();
    },
    fetchArchives() {
      this.loading = true;
      
      const useElasticsearch = this.searchMode === 'elasticsearch';
      const endpoint = useElasticsearch ? '/archive/search' : '/archive/list';
      
      console.log(`使用${useElasticsearch ? 'Elasticsearch' : 'MySQL'}搜索，关键词: ${this.searchQuery}`);
      
      service.get(endpoint, {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          search: this.searchQuery,
          useElasticsearch: useElasticsearch
        }
      })
      .then(res => {
        if (res.data.code === 200) {
          this.archives = res.data.data.records;
          this.totalArchives = res.data.data.total;
          
          if (useElasticsearch && this.searchQuery) {
            this.$message.success(`智能搜索完成，找到 ${this.totalArchives} 条相关档案`);
          }
        } else {
          this.$message.error(res.data.message || '获取档案列表失败');
        }
      })
      .catch(error => {
        console.error("Error fetching archives:", error);
        this.$message.error('获取档案列表失败');
        
        // 如果ES搜索失败，自动切换到MySQL搜索
        if (useElasticsearch) {
          this.$message.warning('智能搜索失败，正在切换到传统搜索...');
          this.searchMode = 'mysql';
          this.elasticsearchAvailable = false;
          setTimeout(() => {
            this.fetchArchives();
          }, 1000);
        }
      })
      .finally(() => {
        this.loading = false;
      });
    },
    async syncToElasticsearch() {
      this.syncing = true;
      try {
        const res = await service.post('/archive/sync/elasticsearch');
        if (res.data.code === 200) {
          this.$message.success('数据同步到Elasticsearch成功');
          // 同步完成后重新搜索
          if (this.searchMode === 'elasticsearch') {
            this.fetchArchives();
          }
        } else {
          this.$message.error(res.data.message || '数据同步失败');
        }
      } catch (error) {
        console.error("同步到Elasticsearch失败:", error);
        this.$message.error('数据同步失败');
      } finally {
        this.syncing = false;
      }
    },
    viewArchiveDetails(archive) {
      this.currentArchive = { ...archive };
      this.detailDialogVisible = true;
    },
    downloadArchive(archive) {
      downloadArchive(
        archive,
        (msg) => this.$message.success(msg),
        (msg) => this.$message.error(msg),
        (msg) => this.$message.warning(msg)
      );
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1; // 重置页码
      this.fetchArchives();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchArchives();
    }
  }
}
</script>

<style scoped>
.archive-storage-retrieval-container {
  padding: 20px;
}

.search-controls {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.search-mode-selector {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  gap: 15px;
}

.es-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-bar {
  width: 100%;
}

.sync-controls {
  margin-top: 10px;
}

.search-tips {
  margin-bottom: 20px;
}

.search-tips ul {
  margin: 8px 0 0 0;
  padding-left: 20px;
}

.search-tips li {
  margin: 4px 0;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 100%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.box-card .el-card__header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-bottom: none;
}

.box-card .el-card__header .clearfix span {
  font-size: 16px;
  font-weight: 500;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #fafafa;
  color: #606266;
  font-weight: 500;
}

.el-pagination {
  text-align: center;
  margin-top: 20px;
}

.ocr-content-section {
  margin-top: 20px;
}

.ocr-content-section h4 {
  margin-bottom: 10px;
  color: #606266;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-mode-selector {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .es-status {
    width: 100%;
    justify-content: space-between;
  }
}
</style> 